package xyz.xxdl.app;


import com.alibaba.fastjson.JSONObject;
import xyz.xxdl.Service.Impl.AsdxApiImpl;
import xyz.xxdl.pojo.Asdx;
import xyz.xxdl.pojo.Result;
import xyz.xxdl.pojo.Trade;
import xyz.xxdl.pojo.TradeGrids;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;


public  class App  implements Runnable{
    public static Asdx asdx;
    public static TradeGrids tradeGrids;
    // 创建api接口对象
    public static AsdxApiImpl api = new AsdxApiImpl();
    // 我的可用币
    public static Double myCoin = 0.0;
    public static Double myBalance = 0.0;
    public static  List<Trade> list=new ArrayList<>();
    @Override
    public void run() {
//      isStart(asdx);
        // 初始化信息
        Result init = init(asdx);
        if (!init.getFlag()){
            System.out.println("账号初始化失败");
            return;
        }
        myBalance = (Double) init.getData();

        if (myBalance<(tradeGrids.getEndZone()*tradeGrids.getQty())){
            // 账户余额不足
            System.out.println("停止运行,余额不足");
            return;
        }
        getList();
        // 初始化成功,可以启动
        if (list==null || list.size()==0){
            System.out.println("数据结构初始化失败");
            return;
        }
        while (true){
//            System.out.println("开始交易");
            //主要的逻辑
            onTrack();

            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
//    public static void isStart(Asdx asdx){
//
//
//        while (true){
//
//        }
//    }
    // 3.遍历列表并交易
    public static void onTrack() {
        // 获取币种的卖一价
        Double marketSell = api.marketSell(tradeGrids.getSymbol());
//        System.out.println("卖一"+marketSell);
        Double marketBuy = api.marketBuy(tradeGrids.getSymbol());
//        System.out.println("买一"+marketBuy);
        // 遍历list,根据市价执行不同的操作
        for (Trade trade : list) {
            if (myBalance>(trade.getBuyPrice()*trade.getQty())&&marketSell>0&&trade.getBuyPrice()>marketSell&&(trade.getBuyPrice()-tradeGrids.getZone()<marketSell) &&!("Filled".equals( trade.getBuyState()))){
                // 有余额,市价不为负,买价大于市价的卖一,卖一位于当前价和上一个买价格的区间,买状态不是filled
                String buy = api.orderNew(tradeGrids.getSymbol(), trade.getBuyPrice().toString(), trade.getQty().toString(), "buy");
                trade.setBuyState(buy);
                myBalance = "Filled".equals(buy)?(myBalance-trade.getBuyPrice()*trade.getQty()):myBalance;
                myCoin = "Filled".equals(buy)?(myCoin+trade.getQty()):myCoin;
            }else if (myCoin>(trade.getQty())&&marketBuy>0&&("Filled".equals( trade.getBuyState()))&&trade.getSellPrice()<marketBuy &&(trade.getSellPrice()+tradeGrids.getZone()>marketBuy)&&!("Filled".equals( trade.getSellState()))){
                // 余额够,买一大于0,买状态是Filled,卖价小于市价的买一,买一价在当前卖价和下一个卖价中,同时卖状态不是filled
                String sell = api.orderNew(tradeGrids.getSymbol(), trade.getBuyPrice().toString(), trade.getQty().toString(), "sell");
                trade.setSellState(sell);
                myBalance = "Filled".equals(sell)?(myBalance+trade.getBuyPrice()*trade.getQty()):myBalance;
                myCoin = "Filled".equals(sell)?(myCoin-trade.getQty()):myCoin;
            }else if (("Filled".equals( trade.getSellState()))&&("Filled".equals( trade.getBuyState()))){
                // 买单和卖单都全部成交了,让age加一,同时重置买/卖状态
                trade.setSellState(null);
                trade.setBuyState(null);
                trade.setAge(trade.getAge()+1);

            }
            else {
                if (marketBuy<0||marketSell<0){
                    // 获取市场价格出错,直接返回
                    break;
                }
                // 什么都不做
            }
        }
    }




    // 2.获取网格数据结构list
    public static void   getList() {

        DecimalFormat df = new DecimalFormat();
        // 集合中要有多少条数据
        int size = (int) ((tradeGrids.getEndZone()-tradeGrids.getStartZone())/tradeGrids.getZone());
        // 构建网格数据结构
        for (int i = 0; i < size; i++) {
            Trade trade = new Trade();
            // 格式话下单数量
            df.applyPattern(tradeGrids.getLotSize());
            trade.setQty(Double.parseDouble(df.format(tradeGrids.getQty())));
            // 格式化下单价格
            df.applyPattern(tradeGrids.getTickSize());
            trade.setBuyPrice(Double.parseDouble(df.format(tradeGrids.getStartZone()+i*tradeGrids.getZone())));
            trade.setSellPrice(Double.parseDouble(df.format(tradeGrids.getStartZone()+i*tradeGrids.getZone()+tradeGrids.getSingleProfit())));
            trade.setAge(0);
            list.add(trade);
        }
    }
    // 1.初始化账户,能否成功获取信息和余额
    public static Result init(Asdx asdx){
        AsdxApiImpl.group=asdx.getGroup();
        AsdxApiImpl.secret=asdx.getSecret();
        AsdxApiImpl.apikey=asdx.getApikey();

        JSONObject info = api.query_prv_account_info();
        try {
            if (info.getIntValue("code")==0){
                // 查询余额
                JSONObject balance = api.query_prv_balance("USDT", "cash", "false");
                JSONObject data = (JSONObject) balance.getJSONArray("data").get(0);
                Double myBalance = data.getDouble("availableBalance");
                System.out.println(myBalance);
                return new Result(true,"初始化成功",myBalance);
            }else {
                return new Result(false,"api错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,e.getMessage());
        }


    }


}
